package com.coai.message.service

import com.coai.message.dto.MessageDto
import com.coai.message.dto.SendMessageRequest
import com.coai.message.model.Message
import com.coai.message.model.MessageType
import com.coai.message.repository.MessageRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.HttpEntity
import org.springframework.http.HttpHeaders
import org.springframework.http.MediaType
import org.springframework.stereotype.Service
import org.springframework.web.client.RestTemplate

/**
 * AI消息服务 - 智能分析和处理消息
 */
@Service
class AIMessageService(
    private val messageRepository: MessageRepository,
    private val messageService: MessageService,
    private val restTemplate: RestTemplate
) {
    
    @Value("\${ai.service.url:http://localhost:8082}")
    private lateinit var aiServiceUrl: String
    
    /**
     * 分析消息并生成AI回复（智能客服场景）
     */
    suspend fun analyzeAndReply(
        conversationId: String,
        message: Message,
        userId: String
    ): MessageDto? = withContext(Dispatchers.IO) {
        
        // 检查是否需要AI介入
        if (!shouldAIIntervene(message)) {
            return@withContext null
        }
        
        // 获取会话历史
        val conversationHistory = getConversationHistory(conversationId, limit = 10)
        
        // 调用AI服务分析
        val aiResponse = callAIService(
            endpoint = "/api/ai/customer-service",
            request = mapOf(
                "customerId" to userId,
                "query" to message.content,
                "conversationHistory" to conversationHistory,
                "messageType" to message.messageType.name
            )
        )
        
        // 解析AI响应
        val responseType = aiResponse["type"] as? String ?: "ANSWER"
        val responseMessage = aiResponse["message"] as? String ?: return@withContext null
        
        // 发送AI回复
        val aiReply = messageService.sendMessage(
            SendMessageRequest(
                conversationId = conversationId,
                messageType = MessageType.AI_REPLY,
                content = responseMessage,
                metadata = mapOf(
                    "aiType" to responseType,
                    "confidence" to (aiResponse["confidence"] ?: 0.9),
                    "intent" to (aiResponse["intent"] ?: "GENERAL")
                ),
                replyToId = message.id
            ),
            senderId = "ai-assistant"
        )
        
        aiReply
    }
    
    /**
     * 会议内容实时分析和总结
     */
    suspend fun analyzeMeetingContent(
        conversationId: String,
        startTime: String,
        endTime: String
    ): MessageDto = withContext(Dispatchers.IO) {
        
        // 获取会议期间的所有消息
        val messages = messageRepository.findByConversationIdOrderByCreatedAtDesc(
            conversationId,
            org.springframework.data.domain.PageRequest.of(0, 1000)
        ).filter { 
            // TODO: 根据startTime和endTime过滤
            true
        }
        
        // 提取文本内容
        val meetingTranscript = messages
            .filter { it.messageType == MessageType.TEXT || it.messageType == MessageType.VOICE }
            .joinToString("\n") { "${it.senderId}: ${it.content}" }
        
        // 调用AI服务进行会议分析
        val aiAnalysis = callAIService(
            endpoint = "/api/ai/meeting-analysis",
            request = mapOf(
                "transcript" to meetingTranscript,
                "conversationId" to conversationId
            )
        )
        
        // 生成会议总结消息
        val summary = buildMeetingSummary(aiAnalysis)
        
        // 发送总结消息
        messageService.sendMessage(
            SendMessageRequest(
                conversationId = conversationId,
                messageType = MessageType.AI_SUMMARY,
                content = summary,
                metadata = mapOf(
                    "summaryType" to "MEETING",
                    "keyPoints" to (aiAnalysis["keyPoints"] ?: emptyList<String>()),
                    "actionItems" to (aiAnalysis["actionItems"] ?: emptyList<String>()),
                    "decisions" to (aiAnalysis["decisions"] ?: emptyList<String>())
                )
            ),
            senderId = "ai-assistant"
        )
    }
    
    /**
     * 智能提取任务
     */
    suspend fun extractTasks(
        conversationId: String,
        messageIds: List<String>
    ): List<MessageDto> = withContext(Dispatchers.IO) {
        
        // 获取指定的消息
        val messages = messageRepository.findAllById(messageIds)
        val content = messages.joinToString("\n") { it.content }
        
        // 调用AI服务提取任务
        val aiResponse = callAIService(
            endpoint = "/api/ai/extract-tasks",
            request = mapOf(
                "content" to content,
                "conversationId" to conversationId
            )
        )
        
        @Suppress("UNCHECKED_CAST")
        val tasks = aiResponse["tasks"] as? List<Map<String, Any>> ?: emptyList()
        
        // 为每个任务创建消息
        tasks.map { task ->
            messageService.sendMessage(
                SendMessageRequest(
                    conversationId = conversationId,
                    messageType = MessageType.AI_TASK,
                    content = buildTaskMessage(task),
                    metadata = mapOf(
                        "taskTitle" to (task["title"] ?: ""),
                        "taskDescription" to (task["description"] ?: ""),
                        "assignee" to (task["assignee"] ?: ""),
                        "deadline" to (task["deadline"] ?: ""),
                        "priority" to (task["priority"] ?: "MEDIUM")
                    )
                ),
                senderId = "ai-assistant"
            )
        }
    }
    
    /**
     * 智能内容生成（商品文案、营销文案等）
     */
    suspend fun generateContent(
        conversationId: String,
        contentType: String,
        params: Map<String, Any>
    ): MessageDto = withContext(Dispatchers.IO) {
        
        // 调用AI服务生成内容
        val aiResponse = callAIService(
            endpoint = "/api/ai/generate-content",
            request = mapOf(
                "contentType" to contentType,
                "params" to params
            )
        )
        
        val generatedContent = aiResponse["content"] as? String ?: ""
        val suggestions = aiResponse["suggestions"] as? List<String> ?: emptyList()
        
        // 发送生成的内容
        messageService.sendMessage(
            SendMessageRequest(
                conversationId = conversationId,
                messageType = MessageType.AI_REPLY,
                content = generatedContent,
                metadata = mapOf(
                    "contentType" to contentType,
                    "suggestions" to suggestions,
                    "keywords" to (aiResponse["keywords"] ?: emptyList<String>())
                )
            ),
            senderId = "ai-assistant"
        )
    }
    
    /**
     * 智能销售助手 - 话术推荐
     */
    suspend fun suggestSalesScript(
        conversationId: String,
        customerId: String,
        context: Map<String, Any>
    ): MessageDto = withContext(Dispatchers.IO) {
        
        // 获取客户画像和对话上下文
        val conversationHistory = getConversationHistory(conversationId)
        
        // 调用AI服务获取话术建议
        val aiResponse = callAIService(
            endpoint = "/api/ai/sales-script",
            request = mapOf(
                "customerId" to customerId,
                "conversationHistory" to conversationHistory,
                "context" to context
            )
        )
        
        val script = aiResponse["script"] as? String ?: ""
        val dealProbability = aiResponse["dealProbability"] as? Double ?: 0.0
        val nextActions = aiResponse["nextBestActions"] as? List<String> ?: emptyList()
        
        // 发送话术建议
        messageService.sendMessage(
            SendMessageRequest(
                conversationId = conversationId,
                messageType = MessageType.AI_REPLY,
                content = "💡 **销售话术建议**\n\n$script\n\n**成交概率**: ${(dealProbability * 100).toInt()}%\n\n**建议下一步行动**:\n${nextActions.joinToString("\n") { "• $it" }}",
                metadata = mapOf(
                    "type" to "SALES_SCRIPT",
                    "dealProbability" to dealProbability,
                    "nextActions" to nextActions
                )
            ),
            senderId = "ai-assistant"
        )
    }
    
    /**
     * 情绪分析
     */
    suspend fun analyzeSentiment(
        conversationId: String,
        message: Message
    ): Map<String, Any> = withContext(Dispatchers.IO) {
        
        callAIService(
            endpoint = "/api/ai/sentiment-analysis",
            request = mapOf(
                "text" to message.content,
                "context" to mapOf(
                    "conversationId" to conversationId,
                    "senderId" to message.senderId
                )
            )
        )
    }
    
    /**
     * 智能消息搜索增强
     */
    suspend fun smartSearch(
        conversationId: String,
        query: String,
        useSemanticSearch: Boolean = true
    ): List<Message> = withContext(Dispatchers.IO) {
        
        if (!useSemanticSearch) {
            // 使用普通搜索
            return@withContext messageRepository.searchByKeyword(
                conversationId,
                query,
                org.springframework.data.domain.PageRequest.of(0, 50)
            )
        }
        
        // 使用AI语义搜索
        val aiResponse = callAIService(
            endpoint = "/api/ai/semantic-search",
            request = mapOf(
                "query" to query,
                "conversationId" to conversationId
            )
        )
        
        @Suppress("UNCHECKED_CAST")
        val messageIds = aiResponse["messageIds"] as? List<String> ?: emptyList()
        
        messageRepository.findAllById(messageIds)
    }
    
    /**
     * 自动翻译消息
     */
    suspend fun translateMessage(
        message: Message,
        targetLanguage: String
    ): String = withContext(Dispatchers.IO) {
        
        val aiResponse = callAIService(
            endpoint = "/api/ai/translate",
            request = mapOf(
                "text" to message.content,
                "targetLanguage" to targetLanguage
            )
        )
        
        aiResponse["translatedText"] as? String ?: message.content
    }
    
    // 辅助方法
    
    private fun shouldAIIntervene(message: Message): Boolean {
        // 判断是否需要AI介入
        // 1. 包含特定关键词（如"客服"、"帮助"、"问题"）
        // 2. 消息来自客户
        // 3. 检测到负面情绪
        val keywords = listOf("客服", "帮助", "问题", "投诉", "退款", "咨询")
        return keywords.any { message.content.contains(it, ignoreCase = true) }
    }
    
    private fun getConversationHistory(
        conversationId: String,
        limit: Int = 20
    ): List<Map<String, String>> {
        val messages = messageRepository.findByConversationIdOrderByCreatedAtDesc(
            conversationId,
            org.springframework.data.domain.PageRequest.of(0, limit)
        )
        
        return messages.reversed().map { msg ->
            mapOf(
                "role" to if (msg.senderId == "ai-assistant") "assistant" else "user",
                "content" to msg.content,
                "timestamp" to msg.createdAt.toString()
            )
        }
    }
    
    private fun callAIService(
        endpoint: String,
        request: Map<String, Any>
    ): Map<String, Any> {
        try {
            val headers = HttpHeaders()
            headers.contentType = MediaType.APPLICATION_JSON
            
            val entity = HttpEntity(request, headers)
            
            @Suppress("UNCHECKED_CAST")
            val response = restTemplate.postForObject(
                "$aiServiceUrl$endpoint",
                entity,
                Map::class.java
            ) as? Map<String, Any> ?: emptyMap()
            
            return response
        } catch (e: Exception) {
            println("AI service call failed: ${e.message}")
            return emptyMap()
        }
    }
    
    private fun buildMeetingSummary(analysis: Map<String, Any>): String {
        val summary = analysis["summary"] as? String ?: ""
        
        @Suppress("UNCHECKED_CAST")
        val keyPoints = analysis["keyPoints"] as? List<String> ?: emptyList()
        @Suppress("UNCHECKED_CAST")
        val actionItems = analysis["actionItems"] as? List<String> ?: emptyList()
        @Suppress("UNCHECKED_CAST")
        val decisions = analysis["decisions"] as? List<String> ?: emptyList()
        
        return buildString {
            appendLine("📊 **会议总结**")
            appendLine()
            appendLine(summary)
            
            if (keyPoints.isNotEmpty()) {
                appendLine()
                appendLine("**关键讨论点**:")
                keyPoints.forEach { appendLine("• $it") }
            }
            
            if (decisions.isNotEmpty()) {
                appendLine()
                appendLine("**决策事项**:")
                decisions.forEach { appendLine("• $it") }
            }
            
            if (actionItems.isNotEmpty()) {
                appendLine()
                appendLine("**待办任务**:")
                actionItems.forEach { appendLine("• $it") }
            }
        }
    }
    
    private fun buildTaskMessage(task: Map<String, Any>): String {
        val title = task["title"] as? String ?: ""
        val description = task["description"] as? String ?: ""
        val assignee = task["assignee"] as? String ?: "待分配"
        val deadline = task["deadline"] as? String ?: "待定"
        val priority = task["priority"] as? String ?: "MEDIUM"
        
        val priorityEmoji = when (priority) {
            "HIGH", "URGENT" -> "🔴"
            "MEDIUM" -> "🟡"
            else -> "🟢"
        }
        
        return buildString {
            appendLine("$priorityEmoji **任务**: $title")
            appendLine()
            appendLine("**描述**: $description")
            appendLine("**负责人**: $assignee")
            appendLine("**截止时间**: $deadline")
            appendLine("**优先级**: $priority")
        }
    }
}
